<script is:inline data-astro-rerun>
  // Artalk 主题同步组件
  (function () {
    // 单例模式存储 Artalk 实例
    window.artalkInstance = window.artalkInstance || null;

    // 基本配置
    const artalkConfig = {
      el: "#Comments",
      server: "https://artalk.lhasa.icu",
      site: "游钓四方的博客",
      pageKey: window.location.pathname,
      vote: false,
    };

    // 独立的评论数统计加载函数
    // 在 loadCommentCount 函数中添加成功标记
    function loadCommentCount() {
      // 检查是否存在评论数统计元素
      const countElements = document.querySelectorAll('.artalk-comment-count');
      if (countElements.length === 0) {
        console.log('页面无评论数统计元素，跳过加载');
        return;
      }
      
      // 确保 Artalk 已加载
      if (typeof Artalk === 'undefined') {
        console.warn('Artalk 尚未加载，延迟加载评论数统计');
        // 增加重试次数限制
        if (!window._artalkCountRetries) window._artalkCountRetries = 0;
        if (window._artalkCountRetries < 10) {
          window._artalkCountRetries++;
          setTimeout(loadCommentCount, 500);
        } else {
          console.error('Artalk加载超时，评论数统计加载失败');
        }
        return;
      }
      
      try {
        // 重置重试计数器
        window._artalkCountRetries = 0;
        
        // 验证所有评论数元素都有data-page-key属性
        let hasValidElements = false;
        countElements.forEach(el => {
          const pageKey = el.getAttribute('data-page-key');
          if (pageKey) {
            hasValidElements = true;
          } else {
            console.warn('发现缺少data-page-key属性的评论数元素:', el);
            // 为缺少属性的元素设置当前页面路径
            el.setAttribute('data-page-key', window.location.pathname);
            hasValidElements = true;
          }
        });
        
        if (!hasValidElements) {
          console.warn('未找到有效的评论数统计元素');
          return;
        }
        
        Artalk.loadCountWidget({
          server: artalkConfig.server,
          site: artalkConfig.site,
          countEl: ".artalk-comment-count",
          statPageKeyAttr: "data-page-key",
        });
        
        // 标记加载成功
        window._artalkCountLoaded = true;
        console.log(`评论数统计已加载，共${countElements.length}个元素`);
      } catch (err) {
        console.error('加载评论数统计失败:', err);
        // 尝试重新加载一次
        if (!window._artalkCountErrorRetry) {
          window._artalkCountErrorRetry = true;
          setTimeout(() => {
            window._artalkCountErrorRetry = false;
            loadCommentCount();
          }, 1000);
        }
      }
    }

    // 获取当前主题状态
    function getCurrentTheme() {
      // 优先检查 data-theme 属性
      const htmlDataTheme = document.documentElement.getAttribute("data-theme");
      if (htmlDataTheme) {
        return htmlDataTheme === "dark";
      }
      
      // 备选方案：检查主题按钮状态
      const themeBtn = document.querySelector("#theme-btn");
      if (themeBtn) {
        const ariaLabel = themeBtn.getAttribute("aria-label");
        if (ariaLabel === "dark" || ariaLabel === "light") {
          return ariaLabel === "dark";
        }
      }
      
      // 最后备选：检查系统偏好
      return window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
    }

    // 销毁 Artalk 实例
    function destroyArtalk() {
      if (window.artalkInstance) {
        try {
          window.artalkInstance.destroy();
          // 清理残留的DOM元素
          document
            .querySelectorAll(".atk-sidebar, .atk-layer-wrap, .atk-layer, .artalk-comment-count")
            .forEach(el => el.remove());
          window.artalkInstance = null;
          console.log("Artalk 实例已销毁");
        } catch (err) {
          console.error("销毁Artalk实例失败:", err);
        }
      }
    }

    // 初始化 Artalk 实例
    function initArtalk() {
      const container = document.getElementById("Comments");
      if (!container) {
        console.warn("Artalk容器未找到");
        return;
      }

      // 如果容器已经包含Artalk实例，跳过初始化
      if (container.querySelector(".atk-app")) {
        console.log("Artalk实例已存在，跳过初始化");
        return;
      }

      // 获取当前主题
      const isDark = getCurrentTheme();
      
      // 更新配置
      const config = {
        ...artalkConfig,
        pageKey: window.location.pathname,
        darkMode: isDark,
      };

      try {
        // 创建新实例
        window.artalkInstance = Artalk.init(config);
        console.log(`Artalk 初始化完成 - 页面: ${window.location.pathname}, 主题: ${isDark ? 'dark' : 'light'}`);
        
        // 初始化完成后立即同步主题（确保主题正确应用）
        setTimeout(() => {
          syncArtalkTheme();
        }, 100);

      } catch (err) {
        console.error("Artalk初始化失败:", err);
      }
    }

    // 同步评论数统计的主题样式
    function syncCommentCountTheme() {
      const countElements = document.querySelectorAll('.comment-count-badge');
      const isDark = getCurrentTheme();
      
      countElements.forEach(element => {
        // 强制重新应用CSS变量，确保主题切换生效
        element.style.display = 'none';
        element.offsetHeight; // 触发重排
        element.style.display = '';
      });
      
      console.log(`评论数统计主题已同步: ${isDark ? 'dark' : 'light'}`);
    }

    // 同步Artalk主题
    function syncArtalkTheme() {
      if (!window.artalkInstance) return;
      
      const isDark = getCurrentTheme();
      try {
        window.artalkInstance.setDarkMode(isDark);
        // 同时同步评论数统计的主题
        syncCommentCountTheme();
        console.log(`Artalk主题已同步: ${isDark ? 'dark' : 'light'}`);
      } catch (err) {
        console.error("同步Artalk主题失败:", err);
      }
    }

    // 设置主题变化监听器
    function setupThemeObserver() {
      // 如果观察器已存在，先断开
      if (window._artalkThemeObserver) {
        window._artalkThemeObserver.disconnect();
      }

      // 创建新的观察器
      window._artalkThemeObserver = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
          if (mutation.type === 'attributes' && mutation.attributeName === 'data-theme') {
            console.log('检测到主题变化');
            // 延迟同步，确保DOM更新完成
            setTimeout(() => {
              syncArtalkTheme();
            }, 50);
          }
        });
      });

      // 观察 html 元素的 data-theme 属性变化
      window._artalkThemeObserver.observe(document.documentElement, {
        attributes: true,
        attributeFilter: ['data-theme']
      });

      // 额外监听主题按钮变化（作为备选方案）
      const themeBtn = document.querySelector("#theme-btn");
      if (themeBtn && !window._artalkBtnObserver) {
        window._artalkBtnObserver = new MutationObserver((mutations) => {
          mutations.forEach((mutation) => {
            if (mutation.attributeName === "aria-label") {
              console.log('检测到主题按钮变化');
              setTimeout(() => {
                syncArtalkTheme();
              }, 50);
            }
          });
        });

        window._artalkBtnObserver.observe(themeBtn, {
          attributes: true,
          attributeFilter: ["aria-label"],
        });
      }
    }

    // 页面加载处理
    function handlePageLoad() {
      console.log('Artalk页面加载处理开始');
      
      // 先销毁旧实例
      destroyArtalk();
      
      // 重置重试计数器
      window._artalkCountRetries = 0;
      window._artalkCountErrorRetry = false;
      
      // 立即同步评论数统计主题
      setTimeout(syncCommentCountTheme, 50);
      
      // 立即尝试加载评论数统计（无论是否有评论容器）
      setTimeout(loadCommentCount, 100);
      
      // 只有在文章页面才初始化完整的评论系统
      const container = document.getElementById("Comments");
      if (container && container.offsetParent !== null) {
        // 等待DOM稳定后初始化评论系统
        setTimeout(() => {
          initArtalk();
          setupThemeObserver();
        }, 200);
      }
      
      // 额外的评论数统计加载保险机制
      setTimeout(() => {
        const countElements = document.querySelectorAll('.artalk-comment-count');
        if (countElements.length > 0) {
          // 只检查是否有元素还显示空值或null，不检查'0'
          const needsReload = Array.from(countElements).some(el => 
            el.textContent === '' || el.textContent === null || el.textContent === undefined
          );
          if (needsReload) {
            console.log('检测到评论数未正确加载，重新尝试');
            loadCommentCount();
          }
        }
      }, 2000);
    }

    // 清理所有观察器
    function cleanupObservers() {
      if (window._artalkThemeObserver) {
        window._artalkThemeObserver.disconnect();
        window._artalkThemeObserver = null;
      }
      if (window._artalkBtnObserver) {
        window._artalkBtnObserver.disconnect();
        window._artalkBtnObserver = null;
      }
    }

    // 页面切换前清理
    function handleBeforeSwap() {
      console.log('Artalk页面切换前清理');
      destroyArtalk();
      cleanupObservers();
    }

    // 单次设置事件监听
    function setupArtalk() {
      if (window._artalkInitialized) return;
      window._artalkInitialized = true;

      // 页面切换事件
      document.addEventListener("astro:before-swap", handleBeforeSwap);
      document.addEventListener("astro:after-swap", handlePageLoad);

      // 初始加载
      if (document.readyState === "complete") {
        handlePageLoad();
      } else {
        document.addEventListener("DOMContentLoaded", handlePageLoad);
      }
      
      // 页面切换时也重新加载评论数统计
      document.addEventListener("astro:after-swap", () => {
        // 重置计数器
        window._artalkCountRetries = 0;
        window._artalkCountErrorRetry = false;
        
        // 多次尝试确保加载成功
        setTimeout(loadCommentCount, 100);
        setTimeout(loadCommentCount, 500);
        setTimeout(loadCommentCount, 1000);
      });
    }

    // 启动Artalk
    setupArtalk();

    // 修改检测逻辑
    setTimeout(() => {
      // 如果已经成功加载过，就不再检测
      if (window._artalkCountLoaded) return;
      
      const countElements = document.querySelectorAll('.artalk-comment-count');
      if (countElements.length > 0) {
        const needsReload = Array.from(countElements).some(el => 
          el.textContent === '' || el.textContent === null || el.textContent === undefined
        );
        if (needsReload) {
          console.log('检测到评论数未正确加载，重新尝试');
          loadCommentCount();
        }
      }
    }, 2000);
  })();
</script>